// 处理异步 获取评论
async function getComment() {
    const response = await fetch("http://localhost:8080/comment/get", {
        method: "GET"
    });

    const data = await response.json();

    // 请求失败
    if (data["result"] == "false") {
        alert(data["message"]);
        return;
    }

    return data["data"];
}

// 创造评论
async function createComment() {
    const commentData = await getComment();

    // 获取容器
    const commentList = document.getElementById("commentList");
    if (commentList == null)
        return false;
    // 清空容器
    commentList.innerHTML = "";

    // 批量生产评论
    commentData.forEach(item => {
        const commentTemplate =`
        <div class="paragraphComment">
            <div class="commmentName">
                <span><i> &#xf007; </i></span>
                <h4> ${item[0]} </h4>
            </div>
            <p> ${item[1]} </p>
        </div>
        `;
        commentList.innerHTML += commentTemplate;
    })
}

createComment();

// 增加评论
function submitComment() {
    const comment = document.getElementById("commentCon");
    const account = localStorage.getItem("account") || "";

    if (!comment || account == "")
        return false;

    // 空评论处理
    // @ts-ignore
    if (comment.value == "") {
        alert(account + "，请勿填写空评论");
        return false;
    }

    // 传输
    fetch("http://localhost:8080/comment/add", {
        method: "POST",
        body: JSON.stringify({
            account: account,
            // @ts-ignore
            comment: comment.value
        })
    })
    .then(response => response.json())
    .then(data => {
        // 没有成功
        if(data["result"] == false) {
            alert(data["message"]);
            return;
        }
        // 成功刷新
        createComment()
        // 清空输入框
        comment.value = ""
    })
}